//
// Created by 86180 on 2025/11/7.
//
#include "sqlite3.h"
#include "admin.h"
#include "data.h"
#include "stdlib.h"
int register_admin(){
    if (db == NULL) {
        fprintf(stderr, "数据库未连接\n");
        return -1;
    }
   Admin a;
    printf("请输入用户名：\n");
    scanf("%s",a.username);
    printf("请输入用户密码：\n");
    scanf("%s",a.password);
     char sql[256];
    char * errmsg=NULL;
    sprintf(sql,"insert into admins (username,password) values ('%s','%s');",a.username,a.password);
     int rc=sqlite3_exec(db,sql,NULL,NULL,&errmsg);
     if(rc!=SQLITE_OK){
         fprintf(stderr,"%s\n", errmsg);
         sqlite3_free(errmsg);
         return -1;
     }
     printf("注册成功!\n");
     return 1;
}
//int login_callback(void * data,int argc,char ** argv,char ** argv_name){
//    int * login_success = (int *)data;
//    if (argc>=2){
//        *login_success = 1;
//    }
//    return 0;
//}
int login_admin() {
    if (db == NULL) {  // 假设 db 是全局数据库连接
        fprintf(stderr, "数据库未连接\n");
        return -1;
    }
    int index=0;
    Admin a;
    printf("请输入管理员名字：\n");
    scanf("%s",a.username);

    printf("请输入管理员密码：\n");
    scanf("%s",a.password);
    const char *sql="select username,password from admins where username=? and password=?;";
    sqlite3_stmt *stmt;
    int rc=sqlite3_prepare_v2(db,sql,-1,&stmt,NULL);
    if(rc!=SQLITE_OK){
        fprintf(stderr,"查询失败：%s\n",sqlite3_errmsg(db));
        return -1;
    }
    sqlite3_bind_text(stmt,1,a.username,-1,SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt,2,a.password,-1,SQLITE_TRANSIENT);
    while(sqlite3_step(stmt)==SQLITE_ROW){
        index=1;
    }
    if(index==1){
        printf("等陆成功！\n");
        sqlite3_finalize(stmt);
        return 1;
    } else{
        printf("登录失败！\n");
    }
    sqlite3_finalize(stmt);
    return 0;
//    //判断数据库是否连接
//    if (db == NULL) {
//        fprintf(stderr, "数据库未连接\n");
//        return -1;
//    }
//    char username[50],password[50];
//    printf("请输入用户名：\n");
//    scanf("%s",username);
//    printf("请输入密码：\n");
//    scanf("%s\n",password);
//   char * errmsg;
//   int rc = sqlite3_exec(db,"select username,password from admins;",
//                         login_callback,NULL,&errmsg);
//    if (rc!=SQLITE_OK){
//        fprintf(stderr,"login_admin:%s\n",errmsg);
//        sqlite3_free(errmsg);
//        return -1;
//    }
//    if ()
//        return 0;
}
int  add_book(){

}
int query_all_books(){

}
int query_book_by_id(){

}
int  update_book_quantity(){

}
int   delete_book(){

}
int logout_admin(){

}